package com.ias.agdis_r.action.security;

import android.annotation.SuppressLint;
import android.app.AlarmManager;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.ias.agdis_r.R;
import com.ias.agdis_r.bean.auth.AuthEnum;
import com.ias.agdis_r.bean.auth.Authority;
import com.ias.agdis_r.bean.message.MessageTemplate;
import com.ias.agdis_r.bean.update.FTPServerInfoBean;
import com.ias.agdis_r.bean.user.UserInfoBean;
import com.ias.agdis_r.db.MyBeanTempDBHelper;
import com.ias.agdis_r.impl.security.SecurityResponseImpl;
import com.ias.agdis_r.manager.DataBaseManager;
import com.ias.agdis_r.manager.EffectManager;
import com.ias.agdis_r.manager.JavaBeanManager;
import com.ias.agdis_r.manager.ServiceManage;
import com.ias.agdis_r.manager.ThreadManager;
import com.ias.agdis_r.module.ParameterModel;
import com.ias.agdis_r.provider.AccountStateProvider;
import com.ias.agdis_r.service.GpsService;
import com.ias.agdis_r.temple.XmlHelper;
import com.ias.agdis_r.terminalmanager.restful.base.endpoint.response.BaseResponse;
import com.ias.agdis_r.terminalmanager.restful.message.endpoint.response.MessageTempletResponse;
import com.ias.agdis_r.terminalmanager.restful.security.endpoint.response.LoginResponse;
import com.ias.agdis_r.util.S;
import com.ias.agdis_r.util.UpdateFile;
import com.ias.agdis_r.util.UpdateUtil;
import com.ias.agdis_r.util.sdcard.WriteLog;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

@SuppressLint("SimpleDateFormat")
public class SecurityResponseAction implements SecurityResponseImpl {
	private Context context = DataBaseManager.getInstance().getContext();
	/**
	 * 接收登录消息应答处理
	 *
	 * @param response
	 */
	@Override
	public boolean receiveRELI(BaseResponse response) {
		try {
			LoginResponse loginResponse = (LoginResponse) response;

			String enb = loginResponse.getLoginResultVO().getEnb();
			String enm = loginResponse.getLoginResultVO().getEnm();
			String rtl = loginResponse.getLoginResultVO().getRtl();
			String rln = loginResponse.getLoginResultVO().getRln();
			String mfg = loginResponse.getLoginResultVO().getMfg();
			String rli = loginResponse.getLoginResultVO().getRli();
			String vnb = loginResponse.getLoginResultVO().getVnb();
			String ttr = loginResponse.getLoginResultVO().getTtr();
			Authority auth = loginResponse.getLoginResultVO().getAuthority();
			FTPServerInfoBean ftpServerInfo =  loginResponse.getLoginResultVO().getFtpserverinfo();
			WriteLog.getInstance().writeLog("FTP:getPriip:"+ftpServerInfo.getPriip()+",getPubip:"+ftpServerInfo.getPubip()+",getPort:"+ftpServerInfo.getPort()+",getUser:"+ftpServerInfo.getUser()+",getPwd:"+ftpServerInfo.getPwd());
			// 检查资源内容
			if (S.isEmpty(rtl)) {
				String message = context.getString(R.string.message_loginFailed_1);
				WriteLog.getInstance().writeLog(message);
				System.out.println(message);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, message, false);
				return false;
			}
			// 检查用户列表权限内容
			else if (auth == null) {
				String message = context.getString(R.string.message_loginFailed_2);
				WriteLog.getInstance().writeLog(message);
				System.out.println(message);
				EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, message, false);
				return false;
			}

            UserInfoBean userInfo = new UserInfoBean();
            userInfo.setEnb(enb);
            userInfo.setEnm(enm);
            userInfo.setRtl(rtl);
            userInfo.setRln(rln);
			userInfo.setRli(rli);
            userInfo.setMfg(mfg);
			userInfo.setVnb(vnb);
			userInfo.setTtr(ttr);
            userInfo.setIsadmin(false);

            // 保存用户列表权限数据
            JavaBeanManager.getInstance().setAuthority(auth);
            // 保存用户数据
            JavaBeanManager.getInstance().saveUserLoginData(userInfo);
			//保存FTP服务器信息
			UpdateFile.getInstance().setFTPServerInfo(ftpServerInfo);

			// 保存用户名
			DataBaseManager.getInstance().insertShared(ParameterModel.T_LAST_USER, ParameterModel.LOGIN_ACCOUNT, enb);
			// 启动GPS服务(需要GPS服务)
			if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_GPSINFO.toString())) {
				ServiceManage.getInstance().startGpsService();
				GpsService gps = ServiceManage.getInstance().getGpsService();
				if (gps != null) {
					gps.startGPS();
					// 开始发送GPS信息
					ThreadManager.getInstance().startGPSThread();
				}
			}
			// 开始发送IQRY信息
			ThreadManager.getInstance().startIQRYThread();
			if (JavaBeanManager.getInstance().adjust_pri(AuthEnum.AI_T_LUGGAGEBARCODE.toString())) {
				//开启行李单号上报线程
				ThreadManager.getInstance().startSendLuggageBarCodeThread();
			}
			ServiceManage.getInstance().setLogon(true);
			WriteLog.getInstance().writeLog(enm + context.getString(R.string.loginSucceed));
			System.out.println(context.getString(R.string.loginSucceed));
			EffectManager.getInstance().ttsPlay(EffectManager.TTS_TYPE_TASK, context.getString(R.string.loginSucceed), false);
            updateAccountStateProvider(userInfo);
//			sendBraodcast(new Intent(ACTION_LOGIN));
			//同步系统时间
			Date servareDate = loginResponse.getHeader().getCurrentTimestamp();
			setDevSysTime(servareDate);
			// 检测升级版本
			UpdateUtil.getInstance().updateVersion(userInfo);

			XmlHelper.getInstance().loadAreaXML();

			return true;

		} catch (Exception e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 设置系统时间
	 * @param servareDate
	 */
	private void setDevSysTime(Date servareDate) {
		String sYear, sMonth, sDay, sHour, sMinute, sSecond;
		// 设置系统日期
		SimpleDateFormat matter=new SimpleDateFormat("yyyyMMddHHmmss");
	    String sTime = matter.format(servareDate);
		if (sTime.length() < 12) {
			return;
		}
		// 设置系统日期
		sYear = sTime.substring(0, 4);
		sMonth = sTime.substring(4, 6);
		sDay = sTime.substring(6, 8);
		sHour = sTime.substring(8, 10);
		sMinute = sTime.substring(10, 12);
		sSecond = sTime.substring(12, 14);
		// 设置系统时间
		String setTime = S.contact(sHour + ":" + sMinute + ":" + sSecond);
		if(S.valueOf(android.os.Build.MODEL).indexOf("NDP")!=-1)
		{
			Calendar c = Calendar.getInstance();
			c.set(Calendar.YEAR, Integer.parseInt(sYear));
	        c.set(Calendar.MONTH, Integer.parseInt(sMonth)-1);
	        c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(sDay));
	        c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sHour));
	        c.set(Calendar.MINUTE, Integer.parseInt(sMinute));
	        c.set(Calendar.SECOND, Integer.parseInt(sSecond));
	        long when = c.getTimeInMillis();
        	if ((when > 0) && (when / 1000 < Integer.MAX_VALUE)) {

                AlarmManager alarmManager = (AlarmManager) DataBaseManager.getInstance().getContext().getSystemService(Context.ALARM_SERVICE);

                alarmManager.setTime(when);

  	        }
		}else if(S.valueOf(android.os.Build.MODEL).indexOf("CIC390")!=-1) {
			Intent intent = new Intent("com.sfexpress.setSystemTime");
			Calendar c = Calendar.getInstance();
			c.set(Calendar.YEAR, Integer.parseInt(sYear));
			c.set(Calendar.MONTH, Integer.parseInt(sMonth)-1);
			c.set(Calendar.DAY_OF_MONTH, Integer.parseInt(sDay));
			c.set(Calendar.HOUR_OF_DAY, Integer.parseInt(sHour));
			c.set(Calendar.MINUTE, Integer.parseInt(sMinute));
			c.set(Calendar.SECOND, Integer.parseInt(sSecond));
			long when = c.getTimeInMillis();
			intent.putExtra("system_time", when);
			DataBaseManager.getInstance().getContext().sendBroadcast(intent);
		}
		WriteLog.getInstance().writeLog(
				context.getString(R.string.setSysTime) + sYear + "-" + sMonth + "-" + sDay + " " + setTime);
		System.out.println(
				context.getString(R.string.setSysTime) + sYear + "-" + sMonth + "-" + sDay + " " + setTime);
	}

	/**
	 * 接收注销消息应答处理
	 *
	 * @param response
	 */
	@Override
	public boolean receiveRELO(BaseResponse response) {
		// TODO Auto-generated method stub
		// 注销
		ServiceManage.getInstance().onLogonOut();
		WriteLog.getInstance().writeLog("RELO注销");
		System.out.println("RELO注销");
//		sendBraodcast(new Intent(ACTION_LOGOUT));
//		sendPttLogoutBraodcast();
        return false;
    }

	/**
	 * 接收短语模板消息
	 * @param response
	 * @return
	 */
	public boolean receiveDYMB(BaseResponse response){

		MessageTempletResponse messageTempResponse = (MessageTempletResponse)response;
		JavaBeanManager.getInstance().saveMSGTemplate(messageTempResponse.getMessageTemplates());
		JavaBeanManager.getInstance().buildMSG();
		saveTemplate(messageTempResponse.getMessageTemplates().getMessagetemplates());
		return true;
	}

	/**
	 * BY QIBO.YU
	 * 保存模板数据到数据库
	 * @param messagetemplates
	 */
	protected void saveTemplate(List<MessageTemplate> messagetemplates) {

		if(!ServiceManage.getInstance().getIsLogon()){
			return;
		}

		MyBeanTempDBHelper<MessageTemplate> beanTempDBHelper = new MyBeanTempDBHelper<MessageTemplate>(
				DataBaseManager.getInstance().getContext(), MessageTemplate.class);

		SQLiteDatabase db = beanTempDBHelper.getWritableDatabase();
		db.execSQL("delete from " + beanTempDBHelper.getTableName());
		for (MessageTemplate template : messagetemplates) {
			beanTempDBHelper.insert(db, template);
		}

		db.close();
		db = null;
		Log.i("C_MESSAGE_TEMPLATE_INIT", "短语模板加载成功");
	}

    /**
     * 启动对讲应用程序
     */
    private void sendPttStartBraodcast(String enb, String pwd,String enm) {
		//设置被停止的应用也能接收到广播
		Intent intent = new Intent("ias.ptt.start");
		intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
		//设置被停止的应用也能接收到广播
		intent.putExtra("id", enb);
		intent.putExtra("name", enm);
		intent.putExtra("password", pwd);
		intent.putExtra("show", false);
		sendBraodcast(intent);
    }

	public void updateAccountStateProvider(UserInfoBean userInfoBean) {

		ContentResolver resolver = DataBaseManager.getInstance().getContext().getContentResolver();
		Uri uri = Uri.parse(AccountStateProvider.PROVIDER_URI);
		resolver.delete(uri, null, null);
		if(userInfoBean!=null){//保存本地的用户信息
			String enb = userInfoBean.getEnb();
			String enm = userInfoBean.getEnm();
			String pwd = "111111";

			ContentValues values = new ContentValues();
			values.put(AccountStateProvider.COLUMN_USER_NAME, enb);
			values.put(AccountStateProvider.COLUMN_NAME, enm);
			values.put(AccountStateProvider.COLUMN_PASSWORLD, pwd);
			values.put(AccountStateProvider.COLUMN_IS_LOGON, true);
			resolver.insert(uri, values);
			sendPttStartBraodcast(enb, pwd, enm);
		}
    }

    /**
     * 启动对讲应用程序
     */
    public void sendPttLogoutBraodcast() {

        Intent intent = new Intent("ias.ptt.logout");
        sendBraodcast(intent);
    }

    /**
     * 发送广播消息
     *
     * @param intent
     */
    private void sendBraodcast(Intent intent) {
        Context context = DataBaseManager.getInstance().getContext();
        if (context != null) {
            //设置被停止的应用也能接收到广播
            intent.setFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
            context.sendBroadcast(intent);
        } else {
            Log.w("C_sys", "sendBraodcast: context is null" + "login state:" + ServiceManage.getInstance().getIsLogon());
        }
    }

}
